package com.topisv.tms.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.topisv.tms.entity.Function;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.Permission;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.Roleperm;
import com.topisv.tms.service.FunctionService;
import com.topisv.tms.service.PermissionService;
import com.topisv.tms.service.RoleService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 角色管理的Controller, 使用Restful风格的Urls:
 * 
 * List page     : GET /role/
 * Create page   : GET /role/create
 * Create action : POST /role/create
 * Update page   : GET /role/update/{id}
 * Update action : POST /role/update
 * Delete action : GET /role/delete/{id}
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseDataTableController{

	private static final int PAGE_SIZE = 50;

	private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("rolename", "账号");
	}

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private FunctionService functionService;
	
	@Autowired
	private PermissionService permissionService;

	@RequestMapping(value = "v2_show")
	public String list() {
		return "role/roleList";
	}
	@RequestMapping(value = "page",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			Page<Role> page = roleService.getRole(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
		}
	}
	@RequestMapping(value = "v2_create", method = RequestMethod.GET)
	public String createForm(Model model) {
		short restype = 0;
		List<Function> functions = functionService.getMenu(restype,"1");
		if(null != functions)
		{
			for(int i=0; i<functions.size(); i++)
			{
				List<Permission> permission = permissionService.findByFunctionId(functions.get(i).getId());
				functions.get(i).setPermissions(permission);
			}
		}
		model.addAttribute("role", new Role());
		model.addAttribute("functions", functions);
		model.addAttribute("action", "create");
		return "role/roleForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Role role, RedirectAttributes redirectAttributes) {
		roleService.saveRole(role);
		Long[] permissions = role.getPermissions();
		if(permissions != null && permissions.length > 0)
		{
			for(int i=0; i<permissions.length; i++)
			{
				Roleperm roleperm = new Roleperm();
				roleperm.setRole(role);
				roleperm.setPermission(permissionService.getPermission(permissions[i]));
				permissionService.saveRoleperm(roleperm);
			}
		}
		redirectAttributes.addFlashAttribute("message", "创建角色成功");
		return "redirect:/role/v2_show";
	}

	@RequestMapping(value = "v2_update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		short restype = -1;
		List<Function> functions = functionService.getMenu(restype,"1");
		if(null != functions)
		{
			for(int i=0; i<functions.size(); i++)
			{
				List<Permission> permission = permissionService.findByFunctionId(functions.get(i).getId());
				functions.get(i).setPermissions(permission);
			}
		}
		List<Permission> permissions = permissionService.findPermByRoleId(id);
		model.addAttribute("permissions", permissions);
		model.addAttribute("functions", functions);
		model.addAttribute("role", roleService.getRole(id));
		model.addAttribute("action", "update");
		return "role/roleForm";
	}
	
	@RequestMapping(value = "getRole", method = RequestMethod.POST)
	public void getRole(HttpServletResponse response) {
		List<Role> roles = roleService.getAllRole();
		
		Map map = new HashMap();
		map.put("roles", roles);
		map.put("status", "1");
		ObjectMapper objectMapper = new ObjectMapper();
		JsonGenerator jsonGenerator = null;
		try {
			//jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
			//jsonGenerator.writeObject(map);    
			objectMapper.writeValue(response.getWriter(), map);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
		}
		
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadRole") Role role, RedirectAttributes redirectAttributes) {
		roleService.saveRole(role);
		Long[] permissions = role.getPermissions();
		if(permissions != null && permissions.length > 0)
		{
			permissionService.deleteRoleperm(role.getId());
			for(int i=0; i<permissions.length; i++)
			{
				Roleperm roleperm = new Roleperm();
				roleperm.setRole(role);
				roleperm.setPermission(permissionService.getPermission(permissions[i]));
				permissionService.saveRoleperm(roleperm);
			}
		}
		redirectAttributes.addFlashAttribute("message", "更新角色成功");
		return "redirect:/role/v2_show";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		permissionService.deleteRoleperm(id);
		roleService.deleteRole(id);
		
		redirectAttributes.addFlashAttribute("message", "删除角色成功");
		return "redirect:/role/v2_show";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadRole")
	public Role getRole(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return roleService.getRole(id);
		}
		return null;
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
